<template>
  <div class="dialog">
    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      center
      destroy-on-close
      @close="close"
    >
      <div class="content">
        <yc-form v-bind="config" v-model="formData" footerHeight="0px"></yc-form>
        <slot></slot>
      </div>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, useSlots, watch } from 'vue'
import ycForm from '@/base-ui/form'
import { useStore } from '@/store'

const store = useStore()
const slot = useSlots()

defineExpose({
  openDialog,
  closeDialog,
  slot
})

interface Props {
  config: any //from表单配置
  modalConfig: any
  pageName: string
  dialogTitle?: string
  otherInfo?: any
}
const props = withDefaults(defineProps<Props>(), {
  dialogTitle: '新建用户',
  otherInfo: {}
})
const dialogFormVisible = ref(false)
function openDialog() {
  dialogFormVisible.value = true
}
function closeDialog() {
  dialogFormVisible.value = false
}

const formData = ref<any>({})
/*notes
  新建用户的时候 传入的formData是个空对象
*/
watch(
  () => props.modalConfig,
  (newValue) => {
    for (const key in props.modalConfig) {
      formData.value[key] = newValue[key]
    }
    console.log(formData.value, 'for')
  }
)

function save() {
  if (Object.keys(props.modalConfig).length) {
    // 编译
    console.log('编辑', formData.value)

    store.dispatch('system/editPageDataAction', {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherInfo },
      id: props.modalConfig.id
    })
    closeDialog()
  } else {
    // 新建
    console.log('新建', formData.value)
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo }
    })
    closeDialog()
  }
}
function close() {
  formData.value = {}
}
</script>

<style lang="less" scoped></style>
